#coding=utf-8
#LightCam 事件恢复关联程序
#init by hfh 20151229

#import multiprocessing,subprocess
import socket,os,time,re,traceback,subprocess,sys,pymongo
import lc_libs

def ClearEvents():
	expr={'Severity':{"$gt":0},'Type':2}
	sortcont=[("_id",pymongo.ASCENDING)]
	opts=db.queryData(status_table,expr,sortcont,0)
	res=db.genResult(opts)
	print res
	for line in res:
		expr={'Node':line['Node'],'AlertGroup':line['AlertGroup'],'AlertKey':line['AlertKey'],'Severity':{"$gt":0}}
		datas={'Severity':0,'SoundStatus':0}
		db.updateData(status_table,expr,datas)

if __name__ == "__main__":


	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	today=time.strftime('%Y%m%d',time.localtime())
	comd="mv %s %s.%s" % (logfilename,logfilename,today)
	os.system(comd)
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()
	
	agent_hostname=lc_libs.lc_gethostname()
	
	try:
		#初始化数据库
		
		db=lc_libs.lc_mongodb_operater('127.0.0.1',27017)

		db.connect()
		Conn=db.getConn()
		if Conn==None:
			print "Can not Connect to the MondbDB"
			exit(0)
		
		alert_dbname='lc_alert'
		status_tablename='lc_status'
		history_tablename="lc_history"
		
		alert_db=db.useDatabase(alert_dbname)
		status_table=db.UseCollection(alert_db,status_tablename)
		history_table=db.UseCollection(alert_db,history_tablename)

	except Exception:
		excinfo=traceback.format_exc()
		logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
		logfile.write(logdate+" 初始化数据库失败:\n"+excinfo+"\n")
		logfile.flush()
		exit(0)


	#TableFields={}
	while True:
		time.sleep(0.1)
		try:
			ClearEvents()
		except Exception:
			excinfo=traceback.format_exc()
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" :\n"+excinfo+"\n")
			logfile.flush()
		time.sleep(5)
	
